<template>
  <div class="parameter-editor h-full flex flex-col bg-gray-50">
    <!-- 主参数设置区域 -->
    <div class="flex-1 bg-white border border-gray-200 rounded-lg m-4">
      <!-- 步骤头部信息 -->
      <div class="p-6 border-b border-gray-200">
        <div class="flex items-center justify-between mb-4">
        <div class="flex items-center">
            <!-- 大号步骤编号 -->
            <div class="w-12 h-12 rounded-full bg-blue-500 text-white flex items-center justify-center text-xl font-bold mr-4">
            {{ currentStep.stepNumber || 1 }}
          </div>
          <div>
              <h2 class="text-xl font-semibold text-gray-800 mb-1">{{ currentStep.name || '输入用户名' }}</h2>
              <p class="text-sm text-gray-500">类型: {{ getStepTypeName(currentStep.type) }}</p>
          </div>
        </div>
          
          <!-- 步骤状态和操作按钮 -->
          <div class="flex items-center space-x-4">
        <div class="flex items-center">
              <span class="text-sm text-gray-500 mr-2">步骤状态:</span>
          <el-select 
            v-model="currentStep.status" 
                size="default"
                class="w-32"
            @change="updateStepData"
          >
            <el-option label="待执行" value="pending" />
            <el-option label="执行中" value="running" />
            <el-option label="已成功" value="success" />
            <el-option label="已失败" value="failed" />
            <el-option label="已跳过" value="skipped" />
          </el-select>
            </div>
            
            <div class="flex items-center space-x-2">
              <el-button type="primary" size="default" @click="moveStep">
                <el-icon class="mr-1"><iEpPlus /></el-icon>
                调整位置
              </el-button>
              <el-button type="danger" size="default" @click="deleteStep">
                <el-icon class="mr-1"><iEpDelete /></el-icon>
                删除步骤
              </el-button>
            </div>
        </div>
      </div>
      
        <!-- 步骤导航 -->
        <div class="flex items-center justify-between">
        <div class="flex items-center">
            <span class="text-sm text-gray-500 mr-3">步骤导航:</span>
          <el-button-group>
            <el-button 
                size="default" 
              :disabled="currentStepIndex <= 0"
              @click="navigateStep(-1)"
            >
              <el-icon><iEpArrowLeft /></el-icon>
            </el-button>
            <el-button 
                size="default" 
              :disabled="currentStepIndex >= totalSteps - 1"
              @click="navigateStep(1)"
            >
              <el-icon><iEpArrowRight /></el-icon>
            </el-button>
          </el-button-group>
            <span class="text-sm text-gray-500 ml-4">
            {{ currentStepIndex + 1 }}/{{ totalSteps }}
          </span>
          </div>
        </div>
      </div>

      <!-- 主要参数设置区域 -->
      <div class="p-6">
        <div class="grid grid-cols-2 gap-6">
          <!-- 定位器 -->
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">定位器</label>
          <div class="flex">
          <el-input
              v-model="currentStep.selector"
              placeholder="CSS选择器或XPath"
                size="default"
              class="flex-1"
              @change="updateStepData"
          />
              <el-button size="default" class="ml-2" @click="pickSelector">
              <el-icon><iEpAim /></el-icon>
            </el-button>
          </div>
        </div>
        
          <!-- 输入值 -->
        <div v-if="showValueInput">
            <label class="block text-sm font-medium text-gray-700 mb-2">输入值</label>
          <el-input
            v-model="currentStep.value"
            placeholder="输入内容"
              size="default"
            @change="updateStepData"
          />
        </div>
        
          <!-- URL地址 -->
        <div v-if="showUrlInput">
            <label class="block text-sm font-medium text-gray-700 mb-2">URL地址</label>
          <el-input
            v-model="currentStep.url"
            placeholder="https://example.com"
              size="default"
            @change="updateStepData"
          />
        </div>
        
          <!-- 等待时间 -->
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">等待时间 (ms)</label>
          <el-input-number
            v-model="currentStep.delay"
            :min="0"
            :step="100"
              size="default"
            class="w-full"
            @change="updateStepData"
          />
        </div>
        
          <!-- 超时时间 -->
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">超时时间 (ms)</label>
          <el-input-number
            v-model="currentStep.timeout"
            :min="1000"
            :step="1000"
              size="default"
            class="w-full"
            @change="updateStepData"
          />
        </div>
      </div>

        <!-- 输入选项 -->
        <div v-if="currentStep.type === 'input'" class="mt-6">
          <h4 class="text-sm font-medium text-gray-700 mb-3">输入选项</h4>
          <div class="space-y-2">
            <el-checkbox 
              v-model="currentStep.options.clearBeforeInput"
              @change="updateStepData"
            >
              先清除现有内容
            </el-checkbox>
            <el-checkbox 
              v-model="currentStep.options.pressEnterAfterInput"
              @change="updateStepData"
            >
              按下回车键
            </el-checkbox>
          </div>
      </div>
      </div>

      <!-- 底部保存按钮 -->
      <div class="p-6 border-t border-gray-200 bg-gray-50 flex justify-end">
        <el-button type="primary" size="default" @click="saveStepChanges">
          <el-icon class="mr-2"><iEpCheck /></el-icon>
          保存更改
        </el-button>
      </div>
      </div>

    <!-- 高级选项区域 - 紧凑设计 -->
    <div class="mx-4 mb-4">
      <!-- 元素树和推荐定位器 - 直接显示，不折叠 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <!-- 元素树面板 - 增强版 -->
        <div class="border border-gray-200 rounded-lg overflow-hidden bg-white">
          <div class="p-3 bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-200 flex items-center justify-between">
            <div class="flex items-center">
              <el-icon class="mr-2 text-blue-600"><iEpMenu /></el-icon>
              <span class="text-sm font-semibold text-gray-700">元素树</span>
            </div>
            <div class="flex space-x-1">
              <el-button size="small" type="primary" text @click="refreshElementTree" title="刷新">
                <el-icon><iEpRefresh /></el-icon>
              </el-button>
              <el-button size="small" type="primary" text @click="toggleElementTree" title="展开/折叠">
                <el-icon><iEpArrowDown /></el-icon>
              </el-button>
              <el-button size="small" type="primary" text @click="inspectElement" title="检查元素">
                <el-icon><iEpSearch /></el-icon>
              </el-button>
                </div>
                </div>
          <div class="p-3 max-h-80 overflow-auto">
            <div class="element-tree">
              <div class="element-item" @click="selectElement('html')">
                <div class="element-line">
                  <el-icon 
                    class="expand-icon" 
                    :class="{ 'expanded': expandedElements.html }"
                    @click.stop="toggleElement('html')"
                  >
                    <iEpArrowRight />
                  </el-icon>
                  <el-icon class="element-icon text-orange-500"><iEpDocument /></el-icon>
                  <span class="element-tag">html</span>
                </div>
                <div v-if="expandedElements.html" class="element-children">
                  <div class="element-item" @click="selectElement('body')">
                    <div class="element-line">
                      <el-icon 
                        class="expand-icon" 
                        :class="{ 'expanded': expandedElements.body }"
                        @click.stop="toggleElement('body')"
                      >
                        <iEpArrowRight />
                      </el-icon>
                      <el-icon class="element-icon text-blue-500"><iEpUser /></el-icon>
                      <span class="element-tag">body</span>
                    </div>
                    <div v-if="expandedElements.body" class="element-children">
                      <div class="element-item" @click="selectElement('div.container')">
                        <div class="element-line">
                          <el-icon 
                            class="expand-icon" 
                            :class="{ 'expanded': expandedElements.container }"
                            @click.stop="toggleElement('container')"
                          >
                            <iEpArrowRight />
                          </el-icon>
                          <el-icon class="element-icon text-green-500"><iEpGrid /></el-icon>
                          <span class="element-tag">div.container</span>
                        </div>
                        <div v-if="expandedElements.container" class="element-children">
                          <div class="element-item" @click="selectElement('input#username')">
                            <div class="element-line">
                              <el-icon class="expand-icon">
                                <iEpArrowRight />
                              </el-icon>
                              <el-icon class="element-icon text-purple-500"><iEpEdit /></el-icon>
                              <span class="element-tag">input#username</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
      </div>

        <!-- 推荐定位器面板 - 增强版 -->
        <div class="border border-gray-200 rounded-lg overflow-hidden bg-white">
          <div class="p-3 bg-gradient-to-r from-green-50 to-emerald-50 border-b border-gray-200 flex items-center justify-between">
            <div class="flex items-center">
              <el-icon class="mr-2 text-green-600"><iEpAim /></el-icon>
              <span class="text-sm font-semibold text-gray-700">推荐定位器</span>
            </div>
            <el-button size="small" type="success" text @click="generateSelectors" title="重新生成">
              <el-icon><iEpRefresh /></el-icon>
            </el-button>
        </div>
          <div class="p-3 max-h-80 overflow-auto">
          <div class="space-y-2">
            <div 
              v-for="(selector, index) in recommendedSelectors" 
              :key="index"
                class="selector-item p-3 border rounded-lg cursor-pointer transition-all duration-200 hover:shadow-md"
                :class="selector.selected ? 'border-blue-500 bg-blue-50 shadow-md' : 'border-gray-200 hover:border-gray-300'"
              @click="selectRecommendedSelector(selector)"
            >
                <div class="flex items-center justify-between">
                  <div class="flex items-center">
                    <el-icon class="mr-3" :class="selector.selected ? 'text-blue-500' : 'text-gray-400'">
                      <iEpCheck v-if="selector.selected" />
                      <iEpCircleCheck v-else />
                    </el-icon>
                    <div>
                      <div class="text-sm font-mono text-gray-800">{{ selector.value }}</div>
                      <div class="text-xs text-gray-500 mt-1">
                        置信度: {{ Math.round(selector.confidence * 100) }}%
                      </div>
                    </div>
                  </div>
                  <div class="flex items-center space-x-2">
                    <el-button size="small" text @click.stop="testSelector(selector)" title="测试">
                      <el-icon><iEpVideoPlay /></el-icon>
                    </el-button>
                    <el-button size="small" text @click.stop="copySelector(selector)" title="复制">
                      <el-icon><iEpCopyDocument /></el-icon>
                    </el-button>
            </div>
          </div>
        </div>
      </div>
      
            <!-- 验证结果 - 增强版 -->
            <div class="mt-4 p-3 bg-gray-50 rounded-lg">
              <div class="flex items-center justify-between mb-2">
              <h3 class="text-sm font-semibold text-gray-700 flex items-center">
                  <el-icon class="mr-2" :class="validationResult.success ? 'text-green-500' : 'text-red-500'">
                    <iEpSuccessFilled v-if="validationResult.success" />
                    <iEpWarningFilled v-else />
                  </el-icon>
                验证结果
              </h3>
              <el-tag 
                :type="validationResult.success ? 'success' : 'danger'" 
                size="small"
              >
                {{ validationResult.success ? '成功' : '失败' }}
              </el-tag>
            </div>
              <div class="text-sm text-gray-700 mb-2">
                {{ validationResult.message }}
            </div>
            <div 
              v-if="validationResult.elementHtml"
                class="bg-gray-900 text-green-400 rounded p-2 font-mono text-xs border overflow-auto max-h-20"
            >
                {{ validationResult.elementHtml }}
            </div>
              <div class="mt-2 flex space-x-2">
                <el-button size="small" @click="revalidateSelector" :loading="validating">
                  <el-icon class="mr-1"><iEpCheck /></el-icon>
                  重新验证
                </el-button>
                <el-button size="small" @click="highlightElement">
                  <el-icon class="mr-1"><iEpView /></el-icon>
                  高亮元素
                </el-button>
              </div>
    </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useScriptStore } from '../stores/script'
import { ElMessage, ElMessageBox } from 'element-plus'

// 步骤配置组件
import NavigationConfig from './stepConfigs/NavigationConfig.vue'
import InputConfig from './stepConfigs/InputConfig.vue'
import ClickConfig from './stepConfigs/ClickConfig.vue'
import AssertionConfig from './stepConfigs/AssertionConfig.vue'
import WaitConfig from './stepConfigs/WaitConfig.vue'
import ScreenshotConfig from './stepConfigs/ScreenshotConfig.vue'

// Element Plus 图标
import { 
  ArrowLeft as iEpArrowLeft,
  ArrowRight as iEpArrowRight,
  ArrowDown as iEpArrowDown,
  Sort as iEpSort,
  Delete as iEpDelete,
  Aim as iEpAim,
  Check as iEpCheck,
  Refresh as iEpRefresh,
  CircleCheck as iEpCircleCheck,
  SuccessFilled as iEpSuccessFilled,
  WarningFilled as iEpWarningFilled,
  InfoFilled as iEpInfoFilled,
  Warning as iEpWarning,
  Search as iEpSearch,
  Document as iEpDocument,
  User as iEpUser,
  Grid as iEpGrid,
  Edit as iEpEdit,
  Menu as iEpMenu,
  VideoPlay as iEpVideoPlay,
  CopyDocument as iEpCopyDocument,
  View as iEpView,
  Plus as iEpPlus
} from '@element-plus/icons-vue'

const scriptStore = useScriptStore()

// 响应式数据
const activeCollapse = ref([])
const currentStepIndex = ref(0)
const expandedElements = ref({
  html: true,
  body: true,
  container: true
})
const selectedElement = ref('input#username')
const validating = ref(false)

// 当前步骤数据
const currentStep = ref({
  stepNumber: 1,
  name: '输入用户名',
  type: 'input',
  selector: '#username',
  value: 'admin@example.com',
  url: '',
  delay: 1000,
  timeout: 5000,
  status: 'pending',
  options: {
    clearBeforeInput: false,
    pressEnterAfterInput: false
  },
  assertion: 'toBeVisible',
  expectedText: '',
  enableCondition: false,
  conditionType: 'element',
  retryCount: 0,
  retryInterval: 1000
})

// 推荐定位器
const recommendedSelectors = ref([
  { value: '#username', selected: true, confidence: 0.95 },
  { value: '.login-form input[type="text"]', selected: false, confidence: 0.85 },
  { value: '//input[@name="username"]', selected: false, confidence: 0.80 },
  { value: 'input[placeholder*="用户名"]', selected: false, confidence: 0.75 }
])

// 验证结果
const validationResult = ref({
  success: true,
  message: '匹配到 1 个元素',
  elementHtml: '<input id="username" type="text" class="login-input" />'
})

// 元素属性
const elementAttributes = ref({
  ID: 'username',
  CLASS: 'login-input',
  TYPE: 'text',
  NAME: 'username',
  PLACEHOLDER: '请输入用户名'
})

// 计算属性
const totalSteps = computed(() => scriptStore.stepCount)

const showValueInput = computed(() => {
  return ['input', 'select', 'assertion'].includes(currentStep.value.type)
})

const showUrlInput = computed(() => {
  return currentStep.value.type === 'navigation'
})

// 监听步骤变化
watch(() => scriptStore.steps, (newSteps) => {
  if (newSteps.length > 0 && currentStepIndex.value < newSteps.length) {
    loadStepData(currentStepIndex.value)
  }
}, { deep: true })

// 监听步骤导入事件
onMounted(() => {
  // 监听步骤导入事件
  const handleStepsImported = (event) => {
    console.log('参数编辑器: 检测到步骤导入事件')
    if (scriptStore.steps.length > 0) {
      currentStepIndex.value = 0
      loadStepData(0)
    }
  }
  
  // 监听步骤选择事件
  const handleStepSelected = (event) => {
    const { index } = event.detail
    if (index >= 0 && index < scriptStore.steps.length) {
      currentStepIndex.value = index
      loadStepData(index)
    }
  }
  
  if (typeof window !== 'undefined') {
    document.addEventListener('stepsImported', handleStepsImported)
    document.addEventListener('stepSelected', handleStepSelected)
  }
  
  // 初始化加载第一个步骤
  if (scriptStore.steps.length > 0) {
    loadStepData(0)
  }
})

// 方法

/**
 * 加载步骤数据
 */
const loadStepData = (stepIndex) => {
  if (stepIndex < 0 || stepIndex >= scriptStore.steps.length) return
  
  const step = scriptStore.steps[stepIndex]
  if (!step) return
  
  // 转换为编辑器格式
  currentStep.value = {
    stepNumber: step.stepNumber || stepIndex + 1,
    name: step.description || step.name || `步骤 ${stepIndex + 1}`,
    type: step.type || 'input',
    selector: step.selector || '',
    value: step.value || '',
    url: step.url || '',
    delay: step.delay || 1000,
    timeout: step.timeout || 5000,
    status: step.status || 'pending',
    options: {
      clearBeforeInput: step.options?.clearBeforeInput || false,
      pressEnterAfterInput: step.options?.pressEnterAfterInput || false
    },
    assertion: step.assertion || 'toBeVisible',
    expectedText: step.expectedText || '',
    enableCondition: step.enableCondition || false,
    conditionType: step.conditionType || 'element',
    retryCount: step.retryCount || 0,
    retryInterval: step.retryInterval || 1000
  }
  
  // 更新推荐定位器
  generateSelectors()
  
  // 验证当前定位器
  validateSelector()
}

/**
 * 更新步骤数据
 */
const updateStepData = () => {
  // 实时更新scriptStore中的步骤数据
  if (currentStepIndex.value >= 0 && currentStepIndex.value < scriptStore.steps.length) {
    const updatedStep = {
      ...scriptStore.steps[currentStepIndex.value],
      stepNumber: currentStep.value.stepNumber,
      name: currentStep.value.name,
      description: currentStep.value.name,
      type: currentStep.value.type,
      selector: currentStep.value.selector,
      value: currentStep.value.value,
      url: currentStep.value.url,
      delay: currentStep.value.delay,
      timeout: currentStep.value.timeout,
      status: currentStep.value.status,
      options: { ...currentStep.value.options },
      assertion: currentStep.value.assertion,
      expectedText: currentStep.value.expectedText,
      enableCondition: currentStep.value.enableCondition,
      conditionType: currentStep.value.conditionType,
      retryCount: currentStep.value.retryCount,
      retryInterval: currentStep.value.retryInterval
    }
    
    // 更新scriptStore
    scriptStore.updateStep(currentStepIndex.value, updatedStep)
  }
  
  // 验证定位器
  validateSelector()
}

/**
 * 处理步骤配置更新
 */
const handleStepConfigUpdate = (configData) => {
  // 合并配置数据到当前步骤
  currentStep.value = {
    ...currentStep.value,
    ...configData
  }
  
  // 更新步骤数据
  updateStepData()
}

/**
 * 步骤导航
 */
const navigateStep = (direction) => {
  const newIndex = currentStepIndex.value + direction
  if (newIndex >= 0 && newIndex < scriptStore.steps.length) {
    currentStepIndex.value = newIndex
    loadStepData(newIndex)
    
    // 触发步骤选择事件
    if (typeof window !== 'undefined') {
      const event = new CustomEvent('stepSelected', {
        detail: { index: newIndex, step: scriptStore.steps[newIndex] }
      })
      document.dispatchEvent(event)
    }
  }
}

/**
 * 保存步骤更改
 */
const saveStepChanges = () => {
  updateStepData()
  
  // 触发步骤更新事件
  if (typeof window !== 'undefined') {
    const event = new CustomEvent('stepUpdated', {
      detail: { 
        index: currentStepIndex.value, 
        step: currentStep.value 
      }
    })
    document.dispatchEvent(event)
  }
  
  ElMessage.success('步骤更改已保存')
}

/**
 * 生成推荐定位器
 */
const generateSelectors = () => {
  const selector = currentStep.value.selector
  if (!selector) return
  
  // 基于当前选择器生成推荐选项
  const selectors = []
  
  // ID选择器
  if (selector.includes('#')) {
    selectors.push({ 
      value: selector, 
      selected: true, 
      confidence: 0.95 
    })
  }
  
  // 类选择器变体
  if (selector.includes('#')) {
    const id = selector.replace('#', '')
    selectors.push({ 
      value: `[id="${id}"]`, 
      selected: false, 
      confidence: 0.90 
    })
    selectors.push({ 
      value: `input#${id}`, 
      selected: false, 
      confidence: 0.85 
    })
  }
  
  // XPath变体
  selectors.push({ 
    value: `//*[@id="${selector.replace('#', '')}"]`, 
    selected: false, 
    confidence: 0.80 
  })
  
  recommendedSelectors.value = selectors
}

/**
 * 选择推荐定位器
 */
const selectRecommendedSelector = (selector) => {
  // 更新选中状态
  recommendedSelectors.value.forEach(s => s.selected = false)
  selector.selected = true
  
  // 更新当前步骤的选择器
  currentStep.value.selector = selector.value
  updateStepData()
}

/**
 * 验证定位器
 */
const validateSelector = async () => {
  const selector = currentStep.value.selector
  if (!selector) {
    validationResult.value = {
      success: false,
      message: '请输入定位器',
      elementHtml: ''
    }
    return
  }
  
  try {
    // 基本语法验证
    const syntaxValidation = validateSelectorSyntax(selector)
    if (!syntaxValidation.valid) {
      validationResult.value = {
        success: false,
        message: `定位器语法错误: ${syntaxValidation.error}`,
        elementHtml: ''
      }
      return
    }
    
    // 模拟后端验证（实际应该调用后端API进行页面元素验证）
    const mockValidation = await mockSelectorValidation(selector)
    
    validationResult.value = mockValidation
    
    // 更新元素属性
    if (mockValidation.success && mockValidation.elementData) {
      elementAttributes.value = mockValidation.elementData.attributes || {}
    }
    
  } catch (error) {
    validationResult.value = {
      success: false,
      message: `验证失败: ${error.message}`,
      elementHtml: ''
    }
  }
}

/**
 * 验证定位器语法
 */
const validateSelectorSyntax = (selector) => {
  try {
    // CSS选择器验证
    if (selector.startsWith('//') || selector.startsWith('(//')) {
      // XPath验证
      if (!selector.match(/^\/\/|^\(\/\//)) {
        return { valid: false, error: 'XPath语法错误' }
      }
    } else {
      // CSS选择器验证
      if (selector.includes('>>')) {
        return { valid: false, error: '不支持 >> 选择器' }
      }
      
      // 检查常见的CSS选择器错误
      if (selector.includes('..')) {
        return { valid: false, error: 'CSS选择器语法错误' }
      }
    }
    
    return { valid: true }
  } catch (error) {
    return { valid: false, error: error.message }
  }
}

/**
 * 模拟定位器验证 - 实际应该调用后端API
 */
const mockSelectorValidation = async (selector) => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 300))
  
  // 模拟不同的验证结果
  if (selector.includes('invalid') || selector.includes('error')) {
    return {
      success: false,
      message: '未找到匹配的元素',
      elementHtml: '',
      elementData: null
    }
  }
  
  if (selector.includes('multiple')) {
    return {
      success: true,
      message: '匹配到 3 个元素（将使用第一个）',
      elementHtml: `<input class="form-control" type="text" />`,
      elementData: {
        count: 3,
        attributes: {
          ID: '',
          CLASS: 'form-control',
          TYPE: 'text',
          NAME: 'input-field'
        }
      }
    }
  }
  
  // 根据选择器类型生成模拟数据
  let mockElement = ''
  let mockAttributes = {}
  
  if (selector.startsWith('#')) {
    const id = selector.replace('#', '')
    mockElement = `<input id="${id}" type="text" class="form-input" />`
    mockAttributes = {
      ID: id,
      CLASS: 'form-input',
      TYPE: 'text',
      NAME: id
    }
  } else if (selector.startsWith('.')) {
    const className = selector.replace('.', '')
    mockElement = `<button class="${className}" type="button">按钮</button>`
    mockAttributes = {
      ID: '',
      CLASS: className,
      TYPE: 'button',
      NAME: ''
    }
  } else if (selector.includes('input')) {
    mockElement = `<input type="text" class="form-control" />`
    mockAttributes = {
      ID: '',
      CLASS: 'form-control',
      TYPE: 'text',
      NAME: 'input-field'
    }
  } else {
    mockElement = `<div class="element">元素</div>`
    mockAttributes = {
      ID: '',
      CLASS: 'element',
      TYPE: 'div',
      NAME: ''
    }
  }
  
  return {
    success: true,
    message: '匹配到 1 个元素',
    elementHtml: mockElement,
    elementData: {
      count: 1,
      attributes: mockAttributes
    }
  }
}

/**
 * 获取步骤类型名称
 */
const getStepTypeName = (type) => {
  const typeNames = {
    navigation: '导航',
    input: '输入文本',
    click: '点击',
    select: '选择',
    wait: '等待',
    assertion: '断言',
    screenshot: '截图'
  }
  return typeNames[type] || type
}

/**
 * 选择器拾取
 */
const pickSelector = () => {
  ElMessage.info('选择器拾取功能需要与浏览器扩展配合使用')
}

/**
 * 移动步骤
 */
const moveStep = () => {
  ElMessage.info('步骤移动功能')
}

/**
 * 删除步骤
 */
const deleteStep = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除步骤 ${currentStep.value.stepNumber}: ${currentStep.value.name} 吗？`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    scriptStore.removeStep(currentStepIndex.value)
    
    // 调整当前步骤索引
    if (currentStepIndex.value >= scriptStore.steps.length) {
      currentStepIndex.value = Math.max(0, scriptStore.steps.length - 1)
    }
    
    // 加载新的当前步骤
    if (scriptStore.steps.length > 0) {
      loadStepData(currentStepIndex.value)
    }
    
    ElMessage.success('步骤已删除')
  } catch {
    // 用户取消删除
  }
}

/**
 * 刷新元素树
 */
const refreshElementTree = () => {
  ElMessage.info('刷新元素树')
}

/**
 * 切换元素树展开/折叠
 */
const toggleElementTree = () => {
  const allExpanded = Object.values(expandedElements.value).every(v => v)
  Object.keys(expandedElements.value).forEach(key => {
    expandedElements.value[key] = !allExpanded
  })
}

/**
 * 选择元素
 */
const selectElement = (elementName) => {
  selectedElement.value = elementName
  // 这里可以添加选择元素的逻辑
}

/**
 * 切换元素展开/折叠
 */
const toggleElement = (elementKey) => {
  expandedElements.value[elementKey] = !expandedElements.value[elementKey]
}

/**
 * 检查元素
 */
const inspectElement = () => {
  ElMessage.info('检查元素功能')
  // 这里可以添加检查元素的逻辑
}

/**
 * 测试选择器
 */
const testSelector = (selector) => {
  ElMessage.info(`测试选择器: ${selector.value}`)
  // 这里可以添加测试选择器的逻辑
}

/**
 * 复制选择器
 */
const copySelector = (selector) => {
  navigator.clipboard.writeText(selector.value).then(() => {
    ElMessage.success('选择器已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

/**
 * 重新验证选择器
 */
const revalidateSelector = async () => {
  validating.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟验证延迟
    await validateSelector()
    ElMessage.success('验证完成')
  } catch (error) {
    ElMessage.error('验证失败')
  } finally {
    validating.value = false
  }
}

/**
 * 高亮元素
 */
const highlightElement = () => {
  ElMessage.info('高亮元素功能')
  // 这里可以添加高亮元素的逻辑
}
</script>

<style scoped>
.parameter-editor {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 步骤编号样式 */
.parameter-editor .step-number {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

/* 输入框样式 */
.parameter-editor :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.parameter-editor :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.parameter-editor :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

/* 按钮样式 */
.parameter-editor :deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.parameter-editor :deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 选择器样式 */
.parameter-editor :deep(.el-select) {
  width: 100%;
}

.parameter-editor :deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
}

/* 数字输入框样式 */
.parameter-editor :deep(.el-input-number) {
  width: 100%;
}

.parameter-editor :deep(.el-input-number .el-input__inner) {
  text-align: left;
  border-radius: 8px;
}

/* 复选框样式 */
.parameter-editor :deep(.el-checkbox) {
  margin-right: 16px;
}

.parameter-editor :deep(.el-checkbox__label) {
  font-size: 14px;
  color: #374151;
}

/* 折叠面板样式 */
.parameter-editor :deep(.el-collapse) {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.parameter-editor :deep(.el-collapse-item__header) {
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  padding: 12px 16px;
  font-weight: 500;
  color: #374151;
}

.parameter-editor :deep(.el-collapse-item__content) {
  padding: 16px;
  background: white;
}

/* 标签样式 */
.parameter-editor :deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
}

/* 卡片悬停效果 */
.parameter-editor .card-hover {
  transition: all 0.2s ease;
}

.parameter-editor .card-hover:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

/* 元素树样式 */
.parameter-editor .element-tree-item {
  transition: all 0.2s ease;
  cursor: pointer;
}

.parameter-editor .element-tree-item:hover {
  background: #f3f4f6;
  border-radius: 4px;
}

/* 推荐定位器样式 */
.parameter-editor .selector-item {
  transition: all 0.2s ease;
  cursor: pointer;
}

.parameter-editor .selector-item:hover {
  transform: translateX(4px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 验证结果样式 */
.parameter-editor .validation-success {
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
}

.parameter-editor .validation-error {
  background: linear-gradient(135deg, #ef4444, #dc2626);
  color: white;
}

/* 元素树样式 - 使用更美观的字体 */
.parameter-editor .element-tree {
  font-family: 'Inter', 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  font-size: 14px;
  line-height: 1.5;
}

.parameter-editor .element-item {
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 6px;
  margin: 2px 0;
  position: relative;
}

.parameter-editor .element-item:hover {
  background: linear-gradient(135deg, #f8fafc, #f1f5f9);
  transform: translateX(2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.parameter-editor .element-line {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  min-height: 32px;
  position: relative;
}

.parameter-editor .expand-icon {
  width: 18px;
  height: 18px;
  margin-right: 10px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  color: #6b7280;
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.parameter-editor .expand-icon:hover {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  transform: scale(1.1);
}

.parameter-editor .expand-icon.expanded {
  transform: rotate(90deg);
  color: #3b82f6;
}

.parameter-editor .element-icon {
  width: 18px;
  height: 18px;
  margin-right: 10px;
  transition: all 0.2s ease;
}

.parameter-editor .element-tag {
  font-size: 14px;
  color: #1f2937;
  font-weight: 500;
  letter-spacing: 0.025em;
  transition: all 0.2s ease;
}

.parameter-editor .element-item:hover .element-tag {
  color: #111827;
  font-weight: 600;
}

.parameter-editor .element-children {
  margin-left: 24px;
  border-left: 2px solid #e5e7eb;
  padding-left: 12px;
  position: relative;
}

.parameter-editor .element-children::before {
  content: '';
  position: absolute;
  left: -1px;
  top: 0;
  bottom: 0;
  width: 1px;
  background: linear-gradient(to bottom, transparent, #e5e7eb 20%, #e5e7eb 80%, transparent);
}

/* 选择器项目样式 */
.parameter-editor .selector-item {
  transition: all 0.2s ease;
  border-radius: 8px;
}

.parameter-editor .selector-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.parameter-editor .selector-item.selected {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.2);
}

/* 验证结果样式 */
.parameter-editor .validation-success {
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
}

.parameter-editor .validation-error {
  background: linear-gradient(135deg, #ef4444, #dc2626);
  color: white;
}

/* 代码高亮样式 */
.parameter-editor .code-highlight {
  background: #1f2937;
  color: #10b981;
  border: 1px solid #374151;
  border-radius: 6px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.4;
}

/* 按钮组样式 */
.parameter-editor .button-group {
  display: flex;
  gap: 4px;
  align-items: center;
}

.parameter-editor .button-group .el-button {
  padding: 4px 8px;
  min-height: 24px;
}

/* 标签样式增强 */
.parameter-editor .element-tag {
  position: relative;
}

.parameter-editor .element-tag::before {
  content: '<';
  color: #6b7280;
}

.parameter-editor .element-tag::after {
  content: '>';
  color: #6b7280;
}

/* 置信度指示器 */
.parameter-editor .confidence-bar {
  width: 100%;
  height: 4px;
  background: #e5e7eb;
  border-radius: 2px;
  overflow: hidden;
  margin-top: 4px;
}

.parameter-editor .confidence-fill {
  height: 100%;
  background: linear-gradient(90deg, #ef4444, #f59e0b, #10b981);
  transition: width 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .parameter-editor .grid-cols-2 {
    grid-template-columns: 1fr;
  }
  
  .parameter-editor .flex.space-x-4 {
    flex-direction: column;
    gap: 1rem;
  }
  
  .parameter-editor .w-1\/2 {
    width: 100%;
  }
  
  .parameter-editor .element-children {
    margin-left: 12px;
  }
  
  .parameter-editor .element-line {
    padding: 2px 4px;
    min-height: 24px;
  }
}
</style>